package org.vs.handler.responsibilitychain.vote;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.vs.annotation.CheckBalance;
import org.vs.contract.VoteContract;
import org.vs.domain.model.TVote;
import org.vs.domain.vo.ProgressVO;
import org.vs.handler.responsibilitychain.BaseResponsibilityChainHandler;
import org.vs.mapper.TVoteMapper;
import org.web3j.protocol.Web3j;
import org.web3j.tx.gas.StaticGasProvider;

import javax.annotation.Resource;

@Slf4j
@Component
public class VotePublishGethHandler extends BaseResponsibilityChainHandler {
    @Resource
    private TVoteMapper voteMapper;

    @Resource
    private Web3j web3j;

    @Resource
    private StaticGasProvider gasProvider;

    @Resource
    private VotePublishInfoHandler votePublishInfoHandler;

    @CheckBalance
    @Override
    protected boolean customerHandler(Object obj) {
        try {
            VotePublishHandlerEO votePublishHandlerEO = (VotePublishHandlerEO) obj;

            votePublishHandlerEO.setCount(votePublishHandlerEO.getCount() + 1);
            setHandler(votePublishInfoHandler);
            setMessage(votePublishHandlerEO.getHashcode(), JSON.toJSONString(ProgressVO
                    .builder()
                    .progress(100 / voteCount)
                    .info("完成合约发布")
                    .build()));

            TVote vote = voteMapper.selectById(votePublishHandlerEO.getPublishDTO().getId());
            VoteContract voteContract = VoteContract
                    .deploy(web3j, votePublishHandlerEO.getCredentials(), gasProvider).send();
            log.info("合约地址 {} ", voteContract.getContractAddress());
            vote.setAddress(voteContract.getContractAddress());
            voteMapper.updateById(vote);
            votePublishHandlerEO.setVote(vote);
            votePublishHandlerEO.setVoteContract(voteContract);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
